package me.fenglu.deployserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorInputStream;
import org.apache.commons.compress.compressors.CompressorStreamFactory;

public class FileDecompressor {
	
	public static void deTar(String destinationPath, String compressType) {
		FileOutputStream fos = null;
		FileInputStream fis = null;
		TarArchiveInputStream tarIn = null;
		
		try {
			
			byte[] buf = new byte[102400];
			
			String rootPath = DeployServer.rootPath;
			fis = new FileInputStream(rootPath + "code.tar.gz");
			CompressorInputStream compressIn = new CompressorStreamFactory().createCompressorInputStream(compressType, fis);
			tarIn = new TarArchiveInputStream(compressIn);
			TarArchiveEntry archiveEntry = null;
			while(null != ( archiveEntry = tarIn.getNextTarEntry())) {
				String fileName = archiveEntry.getName();
				File file = new File(destinationPath+fileName);
				if(archiveEntry.isDirectory()) {
					if(!file.exists()) {
						file.mkdirs();
					}
				}else {
					if(!file.exists()) {
						file.createNewFile();
					}
					fos = new FileOutputStream(destinationPath+fileName);
					int len = 0;
					while(-1 != (len = tarIn.read(buf))) {
						fos.write(buf, 0, len);
						fos.flush();
					}
				}
			}
			
		} catch (CompressorException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
